package com.lepu.app.fun.hospital;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.ImageCompressUtils;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.geneal.UploadMenuImage;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.utils.photo.AppPhotoGridActivity;
import com.core.lib.utils.photo.PhotoInfo;
import com.eyzhs.app.R;
import com.lepu.app.fun.grow.bean.PhotoItem;
import com.lepu.app.fun.hospital.adapter.HospitalAdviceDetailAdapter;
import com.lepu.app.fun.hospital.bean.HospitalAdvice;
import com.lepu.app.fun.hospital.bean.HospitalAdvice.Reply;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.permission.callback.PermissionResultCallBack;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class HospitalAdviceDetailActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest{

	private static final String REQUEST_QUESTION_STATU = "request_question_statu";
	private static final String REQUEST_UPLOAD_DATA = "request_upload_data";
	private static final String REQUEST_DOWNLOAD_DATA = "request_download_data";
	
	private static final int MSG_UPLOAD_DATA_SUCCESS = 10;
	private static final int MSG_UPLOAD_DATA_FAIL = 11;
	private static final int MSG_DOWNLOAD_DATA_SUCCESS = 12;
	private static final int MSG_DOWNLOAD_DATA_FAIL = 13; 
	private static final int MSG_QUESTION_STATU_SUCCESS = 14;
	private static final int MSG_QUESTION_STATU_FAIL = 15; 
	
	private EditText mEditText;
	private Button mSendButton;
	private Button mImageButton;
	private LinearLayout mCommentLayout;
	
	private ListView mListView;
	private ArrayList<Reply> mDataList = new ArrayList<Reply>();
	private ArrayList<String> mImageList = new ArrayList<String>();
	private HospitalAdviceDetailAdapter mAdviceAdapter;

	private HospitalAdvice mHospitalAdvice;
	
	private Timer mTimer = null;
	private boolean mCleanEdit = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hospital_advice_detail_activity);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		
		updateAddImages();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		stopTimer();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setonTopbarNewLeftLayoutListener(this);

		mHospitalAdvice = (HospitalAdvice) getIntent().getSerializableExtra("advice");
		
		mListView = (ListView) findViewById(R.id.consult_listview);
		mEditText = (EditText) findViewById(R.id.consult_editText);
		//mEditText.setFilters(new InputFilter[] { new EmojiFilter(),new InputFilter.LengthFilter(100) });
		mSendButton = (Button) findViewById(R.id.consult_sendbutton);
		mImageButton = (Button) findViewById(R.id.consult_imagebutton);
		mCommentLayout = (LinearLayout) findViewById(R.id.commentLayout);

		mAdviceAdapter = new HospitalAdviceDetailAdapter(HospitalAdviceDetailActivity.this, mDataList, mImageList);
		mListView.setAdapter(mAdviceAdapter);
		
		mSendButton.setOnClickListener(listener);
		mImageButton.setOnClickListener(imageListener);

		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				UtilityBase.closeSoftInput(HospitalAdviceDetailActivity.this);
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		mListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		
		requestQuestionStatus();
		requestDownload();
		showProgressDialog();
		
		startTimer();
	}

	public void startTimer() {
		if (mTimer == null) {
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {

				@Override
				public void run() {
					requestDownload();
	            	mCleanEdit = false;
				}
			}, 60000, 60000);
		}
	}

	public void stopTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer.purge();
			mTimer = null;
		}
	}
	
	View.OnClickListener listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			String sendDate = mEditText.getText().toString().trim();
			if(TextUtils.isEmpty(sendDate)){
				UIHelper.showToast(HospitalAdviceDetailActivity.this, "请输入内容");
				return;
			}
			
			requestUpload(sendDate, null, 1);
			showProgressDialog();
			mCleanEdit = true;
		}
	};

	private void jumpCamera()
	{
		PermissionUtil.getInstance().request(this, new String[]{Manifest.permission.CAMERA,
						Manifest.permission.READ_EXTERNAL_STORAGE,
						Manifest.permission.WRITE_EXTERNAL_STORAGE
				},
				new PermissionResultCallBack() {
					@Override
					public void onPermissionGranted() {
						//
						showPopAddPhoto();
					}

					@Override
					public void onPermissionGranted(String... permissions) {
						if (permissions == null || permissions.length == 0) {
						}
					}

					@Override
					public void onPermissionDenied(String... permissions) {
						if (permissions != null) {

						}
					}

					@Override
					public void onRationalShow(String... permissions) {
						if (permissions != null) {
							UIHelper.showToast(HospitalAdviceDetailActivity.this, R.string.permission_tip);
							PermissionUtil.openSettingActivity(HospitalAdviceDetailActivity.this);
						}
					}
				});
	}
	
	View.OnClickListener imageListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			jumpCamera();
		}
	};
	
	public void showPopAddPhoto() {
		// String temp = SdLocal.getTempPhotoPath(getActivity(),
		// "temp_camera_icon");
		// UploadMenuImage.getInstance(this).setFilePath(temp);
		// UploadMenuImage.getInstance(this).setIsCut(false);
		// UploadMenuImage.getInstance(this).showPopAddPhoto();

		//
		String temp = SdLocal.getTempPhotoPath(HospitalAdviceDetailActivity.this,"temp_camera_icon");
		UploadMenuImage.getInstance(this).setFilePath(temp);
		UploadMenuImage.getInstance(this).setIsCut(false);
		UploadMenuImage.getInstance(this).setIsPhotoDouble(true);

		int selectCount = 1;

		UploadMenuImage.getInstance(this).setPhotoDoubleNum(selectCount);
		UploadMenuImage.getInstance(this).showPopAddPhoto();
	}
	
	
	//照相返回
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		LogUtilBase.LogD(null, "onActivityResult");
		UploadMenuImage.getInstance(this).onActivityResult(new CallBack() {
			@Override
			public void callBackSuccess(Object obj) {
				super.callBackSuccess(obj);
				
				String tempPath = SdLocal.getTempPhotoPath(HospitalAdviceDetailActivity.this, "temp_camera_icon");
				addPhotoItem(tempPath, true);
			}
		}, requestCode, resultCode, data);

	};
	
	//相册返回
	private void updateAddImages() {
		if (AppPhotoGridActivity.mSelectList.size() > 0) {

			for (PhotoInfo item : AppPhotoGridActivity.mSelectList) {

				String tempPath = item.getPath_absolute();
				
				try {
					addPhotoItem(tempPath, false);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			PopUtil.getInstance().dismissPopWindow();
		}
		
		if (AppPhotoGridActivity.mSelectList != null) {
			AppPhotoGridActivity.mSelectList.clear();
		}
	}
	
	private void addPhotoItem(String tempFilePath, boolean isCamera) {
		if (!TextUtils.isEmpty(tempFilePath)) {

			String filePath = SdLocal.getAlbumUserPath(HospitalAdviceDetailActivity.this,
					MyApplication.getInstance().getLoginInfo().UserID,
					String.valueOf(System.currentTimeMillis()));

			boolean flag = false;
			try {
				// tempBitmap = ImageCompressUtils.comp(tempBitmap);
				// ImageUtilBase.saveImageToSd(tempBitmap, filePath);
				ImageCompressUtils.CompressImageFile(tempFilePath, filePath);

				flag = true;
			} catch (Exception e) {
				e.printStackTrace();
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}

			if (!flag) {
				UIHelper.showToast(HospitalAdviceDetailActivity.this, R.string.load_image_fail);
				return;
			}

			if (isCamera) {
				// 删除照相机临时文件
				File tempCameraFile = new File(tempFilePath);
				if (tempCameraFile.exists()) {
					tempCameraFile.delete();
				}
			}

			requestUpload("", filePath, 2);
			
		} else {
			UIHelper.showToast(HospitalAdviceDetailActivity.this, R.string.load_image_fail);
		}
	}
	
	
     //判断问题状态
	 public void requestQuestionStatus() {
		    String url = Setting.getQuestionStatuUrl();
		 
	        Map<String, Object> map = new HashMap<String, Object>();
	        try {
	            JSONObject params = new JSONObject();
	            params.put("DeviceID", Setting.DEVICEID);
	            params.put("ApplicationID", Setting.APPLICATIONID);
	            params.put("UserID", LoginUtil.getUserId());
	            params.put("LoginToken", LoginUtil.getLoginToken());
	            params.put("QuestionID",  mHospitalAdvice.DCQID);
	            map.put("ht", params);
	        } catch (Exception e) {
	        }
	        
	        ApiClient.http_post(url, map, null, this, REQUEST_QUESTION_STATU, true,false,true);

	    }
	
	 
	//上传数据
	public void requestUpload(String sendData, String filePath, int type) {
		
		try {
			//add image
			Map<String, File> fileMaps = null;
			if (!TextUtils.isEmpty(filePath)) {
				String iconPath = SdLocal.getUserPath(this, LoginUtil.getUserId());
				ImageCompressUtils.CompressImageFile(filePath, iconPath);

				fileMaps = new HashMap<String, File>();
				fileMaps.put("MediaFile", new File(iconPath));
			}
			
			//add content
			Map<String, Object> map = new HashMap<String, Object>();
			try {
				JSONObject params = new JSONObject();
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);
				params.put("UserID", LoginUtil.getUserId());
				params.put("LoginToken", LoginUtil.getLoginToken());
				
				params.put("ContentType", type);
				
				params.put("Category", mHospitalAdvice.Category);
				params.put("QuestionID", mHospitalAdvice.DCQID);
				
				if(type == 1){
					params.put("Question", sendData);
				}

				map.put("ht", params);
			} catch (Exception e) {
				e.printStackTrace();
			}

			showProgressDialog();
			ApiClient.http_post(Setting.updateQuestionUrl(), map,fileMaps, this, REQUEST_UPLOAD_DATA, true,false,true);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//下载数据
	public void requestDownload() {

		String url = Setting.downQuestionUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("QuestionID", mHospitalAdvice.DCQID);
			params.put("MaxTime", "");
			map.put("ht", params);
			
		} catch (Exception e) {
		}
		
		ApiClient.http_post(url, map, null, this, REQUEST_DOWNLOAD_DATA, true,false,true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_UPLOAD_DATA_SUCCESS:
				
				requestDownload();

				break;
			case MSG_UPLOAD_DATA_FAIL:
				hideProgressDialog();
				break;

			case MSG_DOWNLOAD_DATA_SUCCESS:
				hideProgressDialog();
				
				if(mCleanEdit){
					mEditText.setText("");
				}
				
				mAdviceAdapter.notifyDataSetChanged();
				mListView.setSelection(mListView.getCount()-1);
				break;
			case MSG_DOWNLOAD_DATA_FAIL:
				hideProgressDialog();
				break;
			case MSG_QUESTION_STATU_SUCCESS:
				String code = (String) msg.obj;
				if(code.equals("0")){
					mCommentLayout.setVisibility(View.VISIBLE);
				}else if(code.equals("1")){
					mCommentLayout.setVisibility(View.GONE);
				}
				break;
			case MSG_QUESTION_STATU_FAIL:
				
				break;
				
			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_UPLOAD_DATA)) {

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_UPLOAD_DATA_SUCCESS;
			mHandler.sendMessage(msg);
			
		}else if(object.equals(REQUEST_DOWNLOAD_DATA)){
			
			ArrayList<Reply> dataArraylist = Reply.parseJsonData((String) data);
			
			mDataList.clear();
			mDataList.addAll(dataArraylist);
			
			mImageList.clear();
			if(mDataList != null && mDataList.size() > 0){
				
				for(int i=0; i<mDataList.size(); i++){
					if(mDataList.get(i).ContentType.equals("2")){
						mImageList.add(mDataList.get(i).ReplyContent);
					}
				}
			}
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DOWNLOAD_DATA_SUCCESS;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_QUESTION_STATU)){
			
			String code = "0";
			try {
				JSONObject jsonObject = new JSONObject((String)data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");
				code = obj2.optString("IsClosed");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_QUESTION_STATU_SUCCESS;
			msg.obj = code;
			mHandler.sendMessage(msg);
			
		}
		
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if(object.equals(REQUEST_UPLOAD_DATA)){
			mHandler.sendEmptyMessage(MSG_UPLOAD_DATA_FAIL);
		}else if(object.equals(REQUEST_DOWNLOAD_DATA)){
			mHandler.sendEmptyMessage(MSG_DOWNLOAD_DATA_FAIL);
		}else if(object.equals(REQUEST_QUESTION_STATU)){
			mHandler.sendEmptyMessage(MSG_QUESTION_STATU_FAIL);
		}
		
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

}
